package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.SafeHtmlCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DocumentDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.Label;

public class DocumentListView extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true) CellTable<DocumentDTO> docTable = new CellTable<DocumentDTO>();
	@UiField SimplePager pager;
	@UiField Button btnAdd;
	@UiField Button btnDel;
	@UiField Button btnBack;
	@UiField Label lbProject;
	@UiField Label lbTask;
	private UploadServiceAsync rpc = GWT.create(UploadService.class);
	private final String forID;
	private final String dataType;
	private String dataType2;
	private final String projectName;
	private final String taskName;
	final MultiSelectionModel<DocumentDTO> selectionModel = new MultiSelectionModel<DocumentDTO>();
	private final ProjTaskServiceAsync projectTaskService = GWT.create(ProjTaskService.class);
	interface Binder extends UiBinder<Widget, DocumentListView> {
	}

	public DocumentListView(String forID, String dataType, String projectName, String taskName) {
		initWidget(binder.createAndBindUi(this));
		this.forID = forID;
		dataType2 = dataType;
		if(dataType.equals("21"))
		{
			this.dataType = "2";
			
		}
		else
		{
			this.dataType = dataType;
		}
		
		this.projectName = projectName;
		this.taskName = taskName;
		this.lbProject.setText("Dự án: " + projectName);
		if(taskName.equals(""))
		{
			this.lbTask.setText("");
		}
		else
		{
			this.lbTask.setText("Công việc: " + taskName);
		}
		
		initTable();
		bindData();
	}

	public void bindData() {

		rpc.getBlobs(forID, dataType, new AsyncCallback<List<DocumentDTO>>() {
			public void onSuccess(List<DocumentDTO> blobData) {
				LoadData(blobData);
			}

			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi xảy ra");
			}
		});
	}

	// Khoi tao Cell Table
	public void initTable() {
		docTable.setSelectionModel(selectionModel, DefaultSelectionEventManager
				.<DocumentDTO> createCheckboxManager());
		Column<DocumentDTO, Boolean> checkColumn = new Column<DocumentDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(DocumentDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		// Description
		TextColumn<DocumentDTO> stt = new TextColumn<DocumentDTO>() {
			@Override
			public String getValue(DocumentDTO myDoc) {
				return myDoc.getIndex() + "";
			}
		};

		// Doc Name
		Column<DocumentDTO, SafeHtml> docName = new Column<DocumentDTO, SafeHtml>(
				new SafeHtmlCell()) {
			@Override
			public SafeHtml getValue(DocumentDTO myDoc) {
				String html = "<a target=\"_blank\" href=" + myDoc.getUrl()
						+ ">" + myDoc.getDocumentName() + "</a>";
				SafeHtml safeHtml = SafeHtmlUtils.fromSafeConstant(html);
				return safeHtml;
			}
		};
		// Description
		TextColumn<DocumentDTO> docDescription = new TextColumn<DocumentDTO>() {
			@Override
			public String getValue(DocumentDTO myDoc) {
				return myDoc.getDescription();
			}
		};
		// Create Date
		TextColumn<DocumentDTO> docCreateDate = new TextColumn<DocumentDTO>() {
			@Override
			public String getValue(DocumentDTO myDoc) {
				return CommonFuntion.convertToDate(new Date(myDoc
						.getCreatedOnDate()));
			}
		};

		// add column
		docTable.setStyleName("ttable");
		docTable.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
		docTable.setColumnWidth(checkColumn, 40, Unit.PX);
		docTable.addColumn(stt, "STT");
		docTable.addColumn(docName, "Tên tài liệu");
		docTable.addColumn(docDescription, "Mô tả");
		docTable.addColumn(docCreateDate, "Ngày upload");

	}

	public void LoadData(List<DocumentDTO> docList) {

		// SimplePager
		pager.setDisplay(docTable);
		pager.setPageSize(5);

		// Create a data provider.
		ListDataProvider<DocumentDTO> dataProvider = new ListDataProvider<DocumentDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(docTable);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		 int count = 1;
		List<DocumentDTO> list = dataProvider.getList();
		for (DocumentDTO doc : docList) {
			doc.setIndex(count);
			count++;
			list.add(doc);		
		}

	}

	@UiHandler("btnAdd")
	void onBtnAddClick(ClickEvent event) {
		UploadDialogView uploadDialog = new UploadDialogView(forID, dataType2, projectName, taskName );
		uploadDialog.setPopupPosition(500, 150);
		uploadDialog.show();
	}

	@UiHandler("btnDel")
	void onBtnDelClick(ClickEvent event) {
		Set<DocumentDTO> listChecked = selectionModel.getSelectedSet();
		List<DocumentDTO> listDoc = new ArrayList<DocumentDTO>();
		for (DocumentDTO doc : listChecked) {
			listDoc.add(doc);
		}
		rpc.deleteDoc(listDoc, new AsyncCallback<Boolean>() {

			@Override
			public void onSuccess(Boolean result) {
				Window.alert("Xóa thành công");
				bindData();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Lỗi xảy ra khi thực hiện xóa !");
			}
		});
	}
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		if(dataType.equals("1"))
		{
			PMEntrypoint.get().PMProjectDetail(forID);
		}
		if(dataType.equals("2"))
		{
			projectTaskService.getTaskById(forID, new AsyncCallback<ProjectTaskDTO>() {
				
				@Override
				public void onSuccess(ProjectTaskDTO result) {
					// TODO Auto-generated method stub

					
					if(dataType2.equals("2"))
					{
						PMEntrypoint.get().PMTaskDetail(result);
					}
					else
					{
						PMEntrypoint.get().PMCreateProjectPlan(result.getProjectId());
						  
					}

				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}
			});
			
		}
	}
}
